package com.fas.hehe.system.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.junit.Assert;

import com.fas.core.BaseController;
import com.fas.core.plugin.jfinal.route.ControllerBind;
import com.fas.hehe.system.model.Attach;
import com.fas.hehe.system.service.AttachService;
import com.jfinal.upload.UploadFile;

/**
 * 
 * @ClassName: AttachController
 * @Description: 文件上传
 * @Copyright: Copyright (c) 2016 FAS
 * @anthor yixiaoping<thinker1013@163.com>
 * @since 2016年2月16日 下午4:24:20
 * @version V1.0
 */
@RequiresAuthentication
@ControllerBind(controllerKey = "/system/attach", viewPath = "/system/attach")
public class AttachController extends BaseController {

	public static String MESSAGE_SUCCESS = "上传成功";
	public AttachService attachService;

	public void ajaxFileUpload() throws Exception {
		List<Attach> attachList = new ArrayList<Attach>();
		String errmsg = MESSAGE_SUCCESS;
		boolean isSuccess = true;
		try {
			List<UploadFile> uploadFiles = this.getFiles();
			Assert.assertTrue("上传表单内容为空!", CollectionUtils.isNotEmpty(uploadFiles));
			attachList = attachService.uploadFile(this.getFiles());
		} catch (Exception e) {
			log.error("上传失败", e);
			isSuccess = false;
			errmsg = "上传失败！失败原因：" + e.getMessage();
		}

		this.returnJsonResult(isSuccess, errmsg, attachList != null ? attachList.get(0) : null);
	}

	public void ajaxFileDelete() {
		String errmsg = null;
		boolean isSuccess = true;
		try {
			isSuccess = attachService.deleteFile(this.getPara("key"));
		} catch (Exception e) {
			log.error("删除失败", e);
			errmsg = "删除失败！失败原因：" + e.getMessage();
		}
		if (errmsg != null) {
			isSuccess = false;
			this.setAttr("error", errmsg);
		}
		this.returnJsonResult(isSuccess);
	}
}
